import axios from "axios";
import axiosAdapterUniapp from "axios-adapter-uniapp";
import { msg } from "@/utils/msg";
import { useKingdeeLogin } from "@/hooks";
const requset = axios.create({
	baseURL: "http://192.168.1.5/k3cloud",
	// baseURL: "http://58.57.52.3:6687/k3cloud",
	//@ts-ignore
	adapter: axiosAdapterUniapp,
	timeout: 30000,
	// withCredentials: true,
});

let isShowLoading = false;

requset.interceptors.request.use(
	(config) => {
		uni.getNetworkType({
			complete: async (res) => {
				let networkType = res.networkType || "none";
				if (networkType === "none")
					return msg("当前无网络,请先检查您的网络状态");

				isShowLoading = Boolean(
					config.data?.isShowLoading || config.data.data?.isShowLoading
				);

				if (isShowLoading) {
					uni.showLoading({
						title: "加载中...",
						mask: true,
					});
				}
				config.headers["kdservice-sessionid"] =
					uni.getStorageSync("kdservice-sessionid") || "";
			}
		})
		return config; // 将配置完成的config对象返回出去 如果不返回 请求讲不会进行
	},
	(err) => {
		// 请求发生错误时的相关处理 抛出错误
		console.log(err);
		Promise.reject(err);
	}
);

requset.interceptors.response.use(
	async (res) => {
		console.log(res);
		if (res?.data?.Result?.ResponseStatus?.ErrorCode == 500 && res?.data?.Result?.ResponseStatus?.Errors[0]?.Message == "会话信息已丢失，请重新登录") {
			uni.clearStorage()
			await useKingdeeLogin()
		}
		if (isShowLoading) {
			uni.hideLoading();
		}
		return Promise.resolve(res);
	},
	(err) => {
		console.log(err);
		uni.hideLoading();
		Promise.reject(err);
	}
);

export default requset;